<?php

class MY_Model extends CI_Model {
	function __construct() {
		parent::__construct();
	}

	function gridFilters($sSortBy, $sDir, $sStart, $sLimit, $aFilters, $bIsExport, $aColumnMapping) {

		// in cazul in care denumirea de coloana e in doua(sau mai multe) tabele in $aColumnMapping se indica maparea de sortare tabel.coloana
		if (is_array($aColumnMapping) && (count($aColumnMapping) > 0)) {
			foreach ($aColumnMapping as $key => $value) {
				if ($value == $sDir) {
					$sSortBy = $key.".".$sSortBy;
					break;
				}
			}
		}

		if (is_array($aFilters)) {
			foreach ($aFilters as $oFilter) {
				$sFieldname = $oFilter->field;

				if (is_array($aColumnMapping) && (count($aColumnMapping) > 0)) {
					foreach ($aColumnMapping as $key => $value) {
						if ($value == $sFieldname) {
							$sFieldname = $key.".".$sFieldname;
							break;
						}
					}
				}

				$sValue = $oFilter->value;
				$sCompare = isset($oFilter->comparison) ? $oFilter->comparison : NULL;
				$sFilterType = $oFilter->type;
				switch ($sFilterType) {
					case 'string' :
						$this->db->like($sFieldname, $sValue);
						break;
					case 'list' :
						if (strstr($sValue, ',')) {
							$aValues = explode(',', $sValue);
							$this->db->where_in($sFieldname, $aValues);
						} else {
							$this->db->where($sFieldname, $sValue);
						}
						break;
					case 'boolean' :
						$this->db->where($sFieldname, $sValue);
						break;
					case 'numeric' :
						switch ($sCompare) {
							case 'eq' :
								$this->db->where($sFieldname, $sValue);
								break;
							case 'lt' :
								$this->db->where($sFieldname.' <', $sValue);
								break;
							case 'gt' :
								$this->db->where($sFieldname.' >', $sValue);
								break;
							case 'gte' :
								$this->db->where($sFieldname.' >=', $sValue);
								break;
							case 'lte' :
								$this->db->where($sFieldname.' <=', $sValue);
								break;
						}
						break;
					case 'date' :
						switch ($sCompare) {
							case 'eq' :
								$this->db->where($sFieldname, date('Y-m-d', strtotime($sValue)));
								break;
							case 'lt' :
								$this->db->where($sFieldname.' <=', date('Y-m-d', strtotime($sValue)));
								break;
							case 'gt' :
								$this->db->where($sFieldname.' >=', date('Y-m-d', strtotime($sValue)));
								break;
						}
						break;
				}

			}
		}
		if (! $bIsExport) {
			$this->db->order_by($sSortBy, $sDir);
			$this->db->limit($sLimit, $sStart);
		} else {
			//Limita maxima de inregistrari
			$this->db->limit(50000);
		}
	}

	function now() {
		return date('Y-m-d H:i:s');
	}

}

/* end */
